﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.QandA;
using TomNet.IMSC.Model.DbModels.QandA;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Controllers.QandA
{
    [Description("百问百答")]
    public class QandAController : BaseController
    {
        public IQandAModelContract QandAContract { get; set; }
        public IQandATypeModelContract QandATypeContract { get; set; }
        #region 列表
        [Description("百问百答-列表")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "", int type = 0)
        {
            try
            {
                var data = from q in QandAContract.Entities.Where(m => !m.IsDeleted)
                           select new
                           {
                               Id = q.Id,
                               ProblemTypeId = (from qt in QandATypeContract.Entities where q.ProblemTypeID == qt.Id && !q.IsDeleted select qt.Id).FirstOrDefault(),
                               ProblemType = (from qt in QandATypeContract.Entities where q.ProblemTypeID == qt.Id && !q.IsDeleted select qt.ProblemType).FirstOrDefault(),
                               Problem = q.Problem,
                               Answer = q.Answer
                           };
                if (!string.IsNullOrWhiteSpace(search))
                {
                    data = data.Where(m => m.Answer.Contains(search));
                }
                if (type != 0)
                {
                    data = data.Where(n => n.ProblemTypeId == type);
                }
                //数据总数
                var total = data.Count();
                //默认给一个排序的字段
                data = data.OrderByDescending(m => m.Id);
                //分页(假如total == 0，则取消分页查询，提高性能)
                data = total > 0 ? data.Skip((pageIndex - 1) * pageSize).Take(pageSize) : data;
                //此处可以采用匿名对象 GridData<object>
                GridData<object> gridData = new GridData<object>() { Total = total, Rows = data.ToList() };
                //此处采用重写后的jsonResult
                return JsonEx(gridData);
            }
            catch
            {
                return JsonEx(new GridData<object>(), JsonRequestBehavior.AllowGet);
            }

        }
        #endregion

        #region 分类添加
        [Description("百问百答-分类添加")]
        public ActionResult InsertClass()
        {
            return View();
        }
        [HttpPost]
        public ActionResult InsertClassAsync(QandATypeModel entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = QandATypeContract.CheckExists(m => m.ProblemType.Equals(entity.ProblemType) && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的分类";
                }
                else
                {
                    var count = QandATypeContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 分类编辑
        [Description("百问百答-分类编辑")]
        public ActionResult EditClass(int id)
        {
            var entity = QandATypeContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditClassAsync(QandATypeModel entity)
        {
            var result = new AjaxResult();
            try
            {
                var query = QandATypeContract.CheckExists(m => m.ProblemType.Equals(entity.ProblemType) && m.Id != entity.Id && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的分类";
                }
                else
                {
                    var count = QandATypeContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 分类删除
        [Description("百问百答-分类删除")]
        [HttpPost]
        public ActionResult DeleteClassAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                QandATypeContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new QandATypeModel { IsDeleted = true });
                QandAContract.UpdateDirect(n => idsInt.Contains(n.ProblemTypeID), n => new QandAModel { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 问题添加
        [Description("百问百答-问题添加")]
        public ActionResult InsertProblem(int type)
        {
            var entity = QandATypeContract.GetByKey(type);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult InsertProblemAsync(QandAModel entity)
        {
            if (entity.Answer == null)
            {
                entity.Answer = "";
            }
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = QandAContract.CheckExists(m => m.Problem.Equals(entity.Problem) && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的问题";
                }
                else
                {
                    var count = QandAContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 问题修改
        [Description("百问百答-问题修改")]
        public ActionResult EditProblem(int id)
        {
            var entity = QandAContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            var qtentity = QandATypeContract.GetByKey(entity.ProblemTypeID);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            ViewData["qtentity"] = qtentity;
            return View();
        }
        [HttpPost]
        public ActionResult EditProblemAsync(QandAModel entity)
        { 
            if (entity.Answer == null)
            {
                entity.Answer = "";
            }
            var result = new AjaxResult();
            try
            {
                var query = QandAContract.CheckExists(m => m.Problem.Equals(entity.Problem) && m.Id != entity.Id && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的问题";
                }
                else
                {
                    var count = QandAContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 问题删除
        [Description("百问百答-问题删除")]
        [HttpPost]
        public ActionResult DeleteProblemAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                QandAContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new QandAModel { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 分类树
        [Description("百问百答-树")]
        public ActionResult CmpTreeAsync()
        {
            var dat = QandATypeContract.Entities;
            var data = QandATypeContract.Entities.Where(m => m.IsDeleted.Equals(false)).Select(m => new
            {
                text = m.ProblemType,
                id = m.Id,
                state = new
                {
                    opened = true,//展示第一个层级下面的node 
                }
            }).ToList();

            return JsonEx(new
            {
                id = "0",
                text = "全部",
                children = data
            });
        } 
        #endregion
    }
}